package com.boot.auth.support.core;

import cn.dev33.satoken.stp.StpInterface;
import com.boot.framework.token.utils.AuthUtils;
import com.boot.system.dto.SysMenuDTO;
import com.boot.system.dto.SysRoleDTO;
import com.boot.system.dto.SysUserDTO;
import com.boot.system.fegin.SysMenuClient;
import com.boot.system.fegin.SysRoleClient;
import com.boot.system.fegin.SysUserClient;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 自定义权限加载接口实现类
 */
@RequiredArgsConstructor
@Component
public class StpInterfaceImpl implements StpInterface {

    private final SysUserClient sysUserClient;

    private final SysMenuClient sysMenuClient;
    private final SysRoleClient sysRoleClient;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object id, String loginType) {
        SysUserDTO sysUser = sysUserClient.selectById((String) id).getData();


        List<SysRoleDTO> sysRoleEntities = sysRoleClient.selectByIds(List.of(StringUtils.split(sysUser.getRoleIds()))).getData();
        List<String> roles = sysRoleEntities
                .stream()
                .map(SysRoleDTO::getRoleCode)
                .toList();
        if (roles.contains("admin")){
            return List.of("*");
        }else {
            List<SysMenuDTO> menuList = sysMenuClient.selectListByRoleIds(new SysMenuDTO(), new ArrayList<>(AuthUtils.getRoles())).getData();

            Set<String> permissionList = new HashSet<>();
            for (SysMenuDTO dto:menuList){
                String permissions = dto.getMeta().getPermissions();
                permissionList.add(permissions);
            }
            return new ArrayList<>(permissionList);
        }
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object id, String loginType) {
        SysUserDTO sysUser = sysUserClient.selectById((String) id).getData();
        List<SysRoleDTO> sysRoleDTOS = sysRoleClient.selectByIds(List.of(StringUtils.split(sysUser.getRoleIds()))).getData();
        return sysRoleDTOS
                .stream()
                .map(SysRoleDTO::getRoleCode)
                .toList();
    }

}
